import { Request, Response, NextFunction } from 'express';

/**
 * 默认异常处理器
 */
export const defaultErrorHandler = (
  error: any,
  request: Request,
  response: Response,
  next: NextFunction
) => {

  if (error.message) {
    console.log('🚧', error.message);
  }

  let stautsCode: number, message: string;

  /**
   * 处理异常
   */
  switch (error.message) {
    case 'NAME_IS_REQUIRED':
      stautsCode = 400;
      message = '请提供用户名';
      break;
    case 'PASSWORD_IS_REQUIRED':
      stautsCode = 400;
      message = '请提供密码';
      break;
    case 'USER_ALREADY_EXIST':
      stautsCode = 409;
      message = '用户名已被占用';
      break;
    case 'USER_DOES_NOT_EXIST':
      stautsCode = 400;
      message = '用户不存在';
      break;
    case 'PASSWORD_DOES_NOT_MATCH':
      stautsCode = 400;
      message = '密码不对';
      break;
    case 'UNAUTHORIZED':
      stautsCode = 401;
      message = '请先登录';
    case 'USER_DOES_NOT_OWN_RESOURCE':
      stautsCode = 403;
      message = '你不能处理这个内容';
      break;
    case 'PAYMENT_EXPIRED':
      stautsCode = 400;
      message = '支付过期了';
      break;
    case 'BAD_REQUEST':
      stautsCode = 400;
      message = '无法处理您的请求';
      break;
    case 'FILE_NOT_FOUND':
      stautsCode = 404;
      message = '文件不存在';
      break;
    default:
      stautsCode = 500;
      message = '服务暂时出了点问题 ~~ 🌴';
      break;
  }

  response.status(stautsCode).send({message})
}
